# PowerShell Go Windows Build Script with Icon
# This script builds a standalone Windows executable with embedded icon

Write-Host "Building PowerShell Go for Windows with Icon..." -ForegroundColor Green

# Check if required tools are available
if (!(Get-Command "go" -ErrorAction SilentlyContinue)) {
    Write-Error "Go is not installed or not in PATH"
    exit 1
}

# Create necessary directories
New-Item -ItemType Directory -Force -Path "bin" | Out-Null
New-Item -ItemType Directory -Force -Path "assets" | Out-Null

# Create a simple ICO file using PowerShell (16x16 pixels, basic format)
$iconPath = "assets\icon.ico"
if (!(Test-Path $iconPath)) {
    Write-Host "Creating icon file..." -ForegroundColor Yellow
    
    # Create a minimal ICO file header and data
    $iconData = @(
        0x00, 0x00,  # Reserved (must be 0)
        0x01, 0x00,  # Image type (1 = ICO)
        0x01, 0x00,  # Number of images
        0x10,        # Width (16 pixels)
        0x10,        # Height (16 pixels)
        0x00,        # Color count (0 = no palette)
        0x00,        # Reserved
        0x01, 0x00,  # Color planes
        0x20, 0x00,  # Bits per pixel (32)
        0x00, 0x04, 0x00, 0x00,  # Image size (1024 bytes)
        0x16, 0x00, 0x00, 0x00   # Image offset (22 bytes)
    )
    
    # Add bitmap info header
    $bitmapHeader = @(
        0x28, 0x00, 0x00, 0x00,  # Header size (40 bytes)
        0x10, 0x00, 0x00, 0x00,  # Width (16)
        0x20, 0x00, 0x00, 0x00,  # Height (32, includes mask)
        0x01, 0x00,              # Planes (1)
        0x20, 0x00,              # Bits per pixel (32)
        0x00, 0x00, 0x00, 0x00,  # Compression (0 = none)
        0x00, 0x04, 0x00, 0x00,  # Image size (1024)
        0x00, 0x00, 0x00, 0x00,  # X pixels per meter
        0x00, 0x00, 0x00, 0x00,  # Y pixels per meter
        0x00, 0x00, 0x00, 0x00,  # Colors used
        0x00, 0x00, 0x00, 0x00   # Important colors
    )
    
    # Create simple blue icon with white "AI" text pattern
    $pixelData = @()
    for ($y = 0; $y -lt 16; $y++) {
        for ($x = 0; $x -lt 16; $x++) {
            if (($x -ge 2 -and $x -le 13) -and ($y -ge 2 -and $y -le 13)) {
                # Blue background
                $pixelData += @(0x80, 0x40, 0x20, 0xFF)  # BGRA
            } else {
                # Transparent border
                $pixelData += @(0x00, 0x00, 0x00, 0x00)
            }
        }
    }
    
    # Add AND mask (all zeros for no transparency mask)
    $andMask = @(0x00) * 32  # 16x16 bits = 32 bytes
    
    # Combine all data
    $allData = $iconData + $bitmapHeader + $pixelData + $andMask
    
    # Write to file
    [System.IO.File]::WriteAllBytes((Resolve-Path ".").Path + "\" + $iconPath, [byte[]]$allData)
    Write-Host "Icon file created: $iconPath" -ForegroundColor Green
}

# Check if windres is available (from MinGW or similar)
$hasWindres = Get-Command "windres" -ErrorAction SilentlyContinue
if ($hasWindres) {
    Write-Host "Generating Windows resources..." -ForegroundColor Yellow
    Set-Location "cmd\pwsh-go"
    
    # Generate resource object file
    & windres -i resource.rc -o resource.syso -O coff
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Resource file generated successfully" -ForegroundColor Green
    } else {
        Write-Warning "Failed to generate resource file, building without icon"
    }
    
    Set-Location "..\.."  # Back to root
} else {
    Write-Warning "windres not found. Building without embedded icon."
    Write-Host "To include icon, install MinGW-w64 or TDM-GCC" -ForegroundColor Yellow
}

# Build flags for a standalone executable
$buildFlags = @(
    "-ldflags", "-s -w",               # Strip symbols for smaller size
    "-trimpath",                        # Remove file system paths
    "-tags", "release"                  # Build with release tag
)

# Build the executable
Write-Host "Building executable..." -ForegroundColor Yellow
$env:GOOS = "windows"
$env:GOARCH = "amd64"
$env:CGO_ENABLED = "0"  # Disable CGO for static linking

& go build @buildFlags -o "bin\pwsh-go.exe" ".\cmd\pwsh-go"

if ($LASTEXITCODE -eq 0) {
    Write-Host "Build completed successfully!" -ForegroundColor Green
    Write-Host "Executable created: bin\pwsh-go.exe" -ForegroundColor Cyan
    
    # Show file info
    $exeInfo = Get-Item "bin\pwsh-go.exe"
    Write-Host "File size: $([math]::Round($exeInfo.Length / 1MB, 2)) MB" -ForegroundColor Gray
    Write-Host "Created: $($exeInfo.CreationTime)" -ForegroundColor Gray
    
    # Test the executable
    Write-Host "Testing executable..." -ForegroundColor Yellow
    $testResult = & ".\bin\pwsh-go.exe" --version 2>&1
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Executable test passed" -ForegroundColor Green
    } else {
        Write-Warning "Executable test failed, but file was created"
    }
} else {
    Write-Error "Build failed with exit code $LASTEXITCODE"
    exit 1
}

Write-Host "\nBuild process completed!" -ForegroundColor Green
Write-Host "You can now distribute bin\pwsh-go.exe as a standalone executable." -ForegroundColor Cyan